package com.cloudeasy.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.server.mapper.UserMapper;
import com.cloudeasy.server.po.Permission;
import com.cloudeasy.server.po.User;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    private final UserRoleService userRoleService;

    public UserService(UserRoleService userRoleService) {
        this.userRoleService = userRoleService;
    }

    /**
     * 根据账号获取账号信息
     *
     * @param account 账号
     * @return {@link User}
     */
    public User getByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new CloudEasyException(ResultCodeEnum.ACCOUNT_NOT_EXISTS);
        }
        return user;
    }

    /**
     * 判断是否有admin角色
     *
     * @param account 账号
     * @return {@link Boolean}
     */
    public Boolean hasAdminRole(String account) {
        String userId = this.getByAccount(account).getId();
        return userRoleService.hasAdminRole(userId);
    }

    /**
     * 获取账号拥有的所有可用权限
     *
     * @param account 账号
     * @return {@link List<Permission>}
     */
    public List<Permission> getEnablePermission(String account) {
        if (!getByAccount(account).getUnlocked()) {
            throw new CloudEasyException(ResultCodeEnum.ACCOUNT_LOCKED);
        }
        String userId = this.getByAccount(account).getId();
        if (userId == null) {
            return null;
        }
        return userRoleService.getEnablePermission(userId);
    }
}
